<template>
  <v-card class="mx-auto">
    <v-toolbar class="d-flex item-center px-2" color="blue-lighten-3">
      <v-avatar :image="userInfo.getHeader()" @click="openHandler" />
    </v-toolbar>
    <!-- 聊天列表 -->
    <div
      v-for="(item, index) in friends"
      :key="index"
      className="w-full h-[10vh] flex px-[4vw] py-[1vh] box-border justify-between"
      @click="toChat(item)"
    >
      <div className="basis-1/6 flex items-center">
        <v-avatar
          :image="
            userInfo.getHeader(item.prependAvatar)
          "
          size="40"
        />
      </div>
      <div className="basis-5/6 *:w-full *:flex *:justify-between">
        <div>
          <div>{{ item.title.name }}</div>
          <div className="text-xs" v-show="item.title.time !== 0">
            {{ timeTips(item.title.time) }}
          </div>
        </div>
        <div>
          <div className="text-gray-500 text-sm">
            <div v-html="item.subtitle.text"></div>
          </div>
          <v-badge
            v-show="item.subtitle.noKnow > 0"
            color="error"
            :content="item.subtitle.noKnow"
            inline
          ></v-badge>
        </div>
      </div>
    </div>
    <!-- 侧边栏 -->
    <NavigationDrawer ref="userInfoBar" @close="closeHandler" />
  </v-card>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { addChatList, getUnreadMsg, selectChatList } from "@/api";
import { useUserInfoStore } from "@/store/userInfo";
import { useIndexDB } from "@/store/indexedDB";
import { useSocketInfoStore } from "@/store/webSocket";
import { useRouter } from "vue-router";
import { timeTips } from "@/utils/timeTips";
import NavigationDrawer from "@/components/navigationDrawer.vue";
import { useConfig } from "@/store/localConfig";

const router = useRouter();

const webSocket = useSocketInfoStore();
const userInfo = useUserInfoStore();
const DB = useIndexDB();
const config = useConfig();

const userInfoBar = ref();

const friends = ref<CHAT.list>([]);

// 跳转聊天
const toChat = (obj: any) => {
  let item: USER.info = {
    id: obj.id,
    username: obj.title.name,
    avatar: obj.prependAvatar,
    sex: obj.sex,
    activeStatus: obj.activeStatus,
  };

  // 添加到会话列表
  addChatList(userInfo.user.id, item.id);
  webSocket.curChatUser = item;

  router.push({ path: "/chatBox", query: { tid: item.id } });
};

// 侧边栏打开
const openHandler = () => {
  userInfoBar.value.userDrawer = true;
  config.userTabbar = false;
};

// 侧边栏关闭回调
const closeHandler = () => {
  config.userTabbar = true;
};

onMounted(() => {
  // 获取未读消息，同步到本地数据库中
  getUnreadMsg(userInfo.user.id).then(async (res) => {
    // 更新聊天列表弹框信息
    // 获取会话列表
    selectChatList(userInfo.user.id).then(async (userList) => {
      // 同步消息到本地数据库
      if (res.length > 0) {
        // 分组
        let msgMap = new Map();
        res.forEach((msg) => {
          if (msgMap.has(msg.fid)) {
            let value = msgMap.get(msg.fid);
            value.push({
              fid: msg.fid,
              tid: msg.tid,
              msg: msg.context,
              time: msg.createTime,
              status: 0,
            });
          } else {
            msgMap.set(msg.fid, [
              {
                fid: msg.fid,
                tid: msg.tid,
                msg: msg.context,
                time: msg.createTime,
                status: 0,
              },
            ]);
          }
        });

        for (let [key, value] of msgMap) {
          let DBkey = userInfo.user.id + ":" + key;
          let historyData = await DB.getData(DBkey);
          if (historyData) historyData.data.push(...value);
          else
            historyData = {
              key: DBkey,
              data: value,
            };
          DB.addOrUpdateMsg(DBkey, historyData);
        }
      }

      // 组合会话列表数据
      let resList = [];
      for (let i of userList) {
        let user = {
          id: i.id,
          prependAvatar: i.avatar,
          title: {
            name: i.username,
            time: 0,
          },
          subtitle: {
            text: "",
            noKnow: 0,
          },
          sex: i.sex,
          activeStatus: i.activeStatus,
        };
        // 查找聊天记录
        let chat = await DB.getData(userInfo.user.id + ":" + i.id);

        if (chat) {
          let data: CHAT.localMsg[] = chat.data;
          // 记录未读信息
          let unread = 0;
          data.length > 0 && data.forEach((i) => i.status === 0 && unread++);
          user.subtitle.noKnow = unread;
          user.subtitle.text = data[data.length - 1].msg;
          user.title.time = data[data.length - 1].time;
        } else {
          user.subtitle.text = "暂无消息";
        }
        resList.push(user);
      }

      friends.value = resList;
    });
  });
});
</script>
